import { getAction } from "@tapui/utils/http"
import AsyncValidator from 'async-validator'
import { noop, getPropByPath } from 'element-ui/src/utils/util'
import objectAssign from 'element-ui/src/utils/merge'
export const mixin_page_fields_custom = {
  methods: {
    getFilteredRule(trigger, fieldItem) {
      const rules = fieldItem.getRules()
      return rules.filter(rule => {
        if (!rule.trigger || trigger === '') return true
        if (Array.isArray(rule.trigger)) {
          return rule.trigger.indexOf(trigger) > -1
        } else {
          return rule.trigger === trigger
        }
      }).map(rule => objectAssign({}, rule))
    },
    // 设置页面字段的自定义配置
    /*
     * editPageCode:页面编码
     * formType:组件类型，目前仅支持el-form，默认也是el-form,后续类型有待开发
     */
    getFieldsCustomSetting(editPageCode, formType) {
      var that = this
      if (this.$refs.form) {
        getAction("mis/vuePageFieldInfo/list", {
          qry_pageCode: editPageCode
        }).then((res) => {
          if (!formType || formType === "el-form") {
            // 获取所有页面字段
            var fieldList = this.$refs.form.fields
            // 遍历返回的字段，如果返回字段中又和页面中字段吻合，则对字段做自定义操作
            res.result.dataList.forEach((resultItem) => {
              // 遍历字段
              fieldList.forEach((fieldItem) => {
                // 处理标签为 el-input的placeholder
                if (fieldItem.$children[1].$options._componentTag === "el-input" && fieldItem.prop === resultItem.code) {
                  var input = fieldItem.$children[1].getInput()
                  // 处理标签为 el-input的placeholder
                  if (resultItem.placeholder) {
                    input.placeholder = resultItem.placeholder
                  }
                  // 如果此input的值为空，则赋默认值 则赋默认值 则赋默认值 则赋默认值则赋默认值则赋默认值则赋默认值 则赋默认值 则赋默认值 则赋默认值
                  if (!input.value) {
                    that.$set(that.model, fieldItem.prop, resultItem.defaultvalue)
                  }
                  // 设置label 设置label 设置label 设置label 设置label 设置label 设置label 设置label 设置label 设置label
                  if (resultItem.name) {
                    fieldItem.$children[0].$el.innerText = resultItem.name
                  }
                  // 设置必填项 设置必填项 设置必填项 设置必填项 设置必填项 设置必填项 设置必填项 设置必填项 设置必填项
                  if (resultItem.required === "1") {
                    var forItemDom = fieldItem.$el
                    forItemDom.classList.add("is-required")
                    // 重写getRules，将自定义的必填rule返回
                    fieldItem.getRules = () => {
                      const selfRules =
                      {
                        required: 'true',
                        message: '请填写' + fieldItem.$children[0].$el.innerText + '内容',
                        trigger: 'change'
                      }
                      const requiredRule = fieldItem.required !== undefined ? {
                        required: !!fieldItem.required
                      } : []
                      return [].concat(selfRules).concat(requiredRule)
                    }
                    // 重写el-form-item的校验方法逻辑，只需要在最后页面渲染完成后，添加星号，从写此方法是为了解决星号丢失问题
                    fieldItem.validate = (trigger, callback = noop) => {
                      fieldItem.validateDisabled = false
                      const rules = fieldItem.getFilteredRule(trigger, fieldItem)
                      if ((!rules || rules.length === 0) && fieldItem.required === undefined) {
                        callback()
                        return true
                      }
                      fieldItem.validateState = 'validating'
                      const descriptor = {}
                      if (rules && rules.length > 0) {
                        rules.forEach(rule => {
                          delete rule.trigger
                        })
                      }
                      descriptor[fieldItem.prop] = rules
                      const validator = new AsyncValidator(descriptor)
                      const model = {}
                      model[fieldItem.prop] = fieldItem.fieldValue
                      validator.validate(model, {
                        firstFields: true
                      }, (errors, invalidFields) => {
                        fieldItem.validateState = !errors ? 'success' : 'error'
                        fieldItem.validateMessage = errors ? errors[0].message : ''
                        callback(fieldItem.validateMessage, invalidFields)
                        fieldItem.elForm && fieldItem.elForm.$emit('validate', fieldItem.prop, !errors, fieldItem.validateMessage || null)
                      })
                      fieldItem.$nextTick(() => {
                        var fieldItemDom = fieldItem.$el
                        fieldItemDom.classList.add("is-required")
                      })
                    }
                  }
                }
                // 处理标签为 el-input 的默认值
                // if (fieldItem.$children[1].$options._componentTag === "el-input" && fieldItem.prop === resultItem.code) {
                //   var input = fieldItem.$children[1].getInput()
                //   input.placeholder = resultItem.placeholder
                // }
              })
              this.$nextTick(() => {
                this.$refs.form.clearValidate()
              })
            })
          }
        })
      }
    }
  }
}
